import { message } from "antd";
import { useRef, useState, type ChangeEvent, type DragEvent } from "react";
import clsm from "@/lib/utils/clsm";
import useOnUpdated from "@/lib/hooks/useOnUpdated";
import useLatestRef from "@/lib/hooks/useLatestRef";
import UploadIcon from "@/assets/icons/upload.svg?jsx";
import FileSelector from "@/components/FileSelector";

type FileSelectorProps = {
  onFileChange?: (file: File | undefined) => void;
};
export default function UploadImage(props: FileSelectorProps) {
  const { onFileChange } = props;
  const [file, setFile] = useState<File>();
  const [preview, setPreview] = useState<string>();

  const onFileChangeRef = useLatestRef(onFileChange);
  useOnUpdated(() => {
    onFileChangeRef.current?.(file);
    if (!file) {
      setPreview(undefined);
      return;
    }
    const url = URL.createObjectURL(file);
    setPreview(url);
    return () => {
      URL.revokeObjectURL(url);
    };
  }, [file]);

  return (
    <FileSelector
      validator={(file) => {
        if (!/^image\/.+/.test(file.type)) {
          message.error("不是一个有效的图像文件！");
          return false;
        }
        return true;
      }}
      onFileChange={setFile}
      className={({ isDragOver }) =>
        clsm(
          "flex size-40 flex-col items-center justify-center rounded border border-dashed border-zinc-500 transition-colors hover:border-sky-500 hover:text-sky-500",
          isDragOver && "border-sky-500 text-sky-500",
        )
      }
    >
      {(file) => (
        <>
          {file ? (
            <img src={preview} alt={file.name} className="max-h-24 max-w-32" />
          ) : (
            <UploadIcon className="size-12" />
          )}
          <p className="mt-4 px-6 text-center text-xs">
            {file ? `已选择：${file.name}` : "点击选择文件或将文件拖拽到此处"}
          </p>
        </>
      )}
    </FileSelector>
  );
}
